import React, { Component } from 'react'

import style from './index.module.styl'
import List from './List'
import Total from './Total'

export default class TodoList extends Component {
  state = {
    todoList: [],
  }

  /**
   *
   * @param {KeyboardEvent} ev
   */
  handleKeyDown = (ev) => {
    if (ev.key === 'Enter') {
      //添加TODO
      this.setState({
        todoList: [
          {
            id: Date.now(),
            name: ev.target.value,
            done: false,
          },
          ...this.state.todoList,
        ],
      })
      ev.target.value = ''
      ev.stopPropagation()
    }
  }

  handleCheckChange = (item, index) => {
    item.done = !item.done
    this.setState({
      todoList: this.state.todoList,
    })
  }

  handleOnDelete = (item, index) => {
    if (window.confirm('确认删除？')) {
      this.setState({
        todoList: this.state.todoList.filter((val) => val.id !== item.id),
      })
    }
  }

  onAllSelectChange = (checked) => {
    if (!checked) {
      // 已经全选，则需要全部取消
      this.state.todoList.forEach((item) => {
        item.done = false
      })
    } else {
      // 全选
      this.state.todoList.forEach((item) => {
        item.done = true
      })
    }
    this.setState({
      todoList: this.state.todoList,
    })
  }

  onClearCompleted = () => {
    this.setState({
      todoList: this.state.todoList.filter((val) => !val.done),
    })
  }

  render() {
    const { todoList } = this.state
    return (
      <div className={style.todo}>
        <input
          type="text"
          placeholder="请输入你的任务名称，按回车确认"
          onKeyDown={this.handleKeyDown}
        />
        <List
          list={todoList}
          onCheckClick={this.handleCheckChange}
          onDelete={this.handleOnDelete}
        />
        <Total
          list={todoList}
          onAllSelectChange={this.onAllSelectChange}
          onClearCompletedClick={this.onClearCompleted}
        />
      </div>
    )
  }
}
